package reentrantlock;

import threadpool.ThreadPoolFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockCounter {

    private final Lock lock = new ReentrantLock();

    private int count;

    public int getCount() {
        return count;
    }

    public void add(int n) {
        lock.lock();
        try {
            Thread.sleep(10);
            count += n;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReentrantLockCounter counter = new ReentrantLockCounter();
        ExecutorService threadPool = ThreadPoolFactory.getThreadPool();
        for (int i = 0; i < 100; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    counter.add(1);
                }
            });
        }
        Thread.sleep(2000);
        threadPool.shutdown();
        System.out.println(counter.getCount());
    }

}
